// var apiHost = 'http://10.132.141.125:8848';
// var apiHost ="http://10.39.3.123:8849";
// var apiHost ="http://elf.data.sina.com.cn:8347";
// var apiHost = 'http://localhost:8848';
// var apiHost = 'http://ubuntu4:8848';
var apiHost = '';
var getDemoArticlesUri = '/v1/demo/getDemoArticles';
var queriesUri = '/v1/images/queries';

function $id(id){ return document.getElementById(id);}//封装的$id(id)函数

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};
var articles;
var userArticles = [];
window.onload = function(){

    tagSection = $("#tagSection");

    // $("section.star_box_s").children().forEach(function (ele) {
    //     ele.click(function(){
    //         console.log($(this).data("score"));
    //     });
    // });


    //prepare articles list
    var isFirst = true;
    $.ajax({
        url: apiHost + getDemoArticlesUri,
        dataType: 'json',
        success: function(res){
            articles = res;
            var articleList = $("#v-pills-tab");
            articleList.html('');
            res.forEach(function (item, index) {
                var node = generateArticleItemHtml(item, index, isFirst, res);
                if (isFirst) {
                    isFirst = false;
                }
                articleList.append(node);
            });
            fillArticlePanel(articles[0]);
        }
    });
};

function filterArticlesByCategory(category) {
    var res = articles;
    if (category === 0) {
        res = userArticles;
    }

    var isFirst = true;
    var articleList = $("#v-pills-tab");
    articleList.html('');
    res.forEach(function (item, index) {
        if (category <= 0 || item.docCategory === category) {
            var node = generateArticleItemHtml(item, index, isFirst, res);
            if (isFirst) {
                isFirst = false;
                fillArticlePanel(item);
            }
            articleList.append(node);
        }
    })
}

function generateArticleItemHtml(item, index, isFirst, res) {
    var html;
    if(isFirst){
        html = '<a class="nav-link active" data-toggle="pill" role="tab" aria-controls="v-pills-home" data-index="'+index+'" aria-selected="true">'+item.title+'</a>';
    }else{
        html = '<a class="nav-link" data-toggle="pill" role="tab" aria-controls="v-pills-home" data-index="'+index+'" aria-selected="true">'+item.title+'</a>';
    }
    var node = $(html);
    node.click(function(){
        var index = $(this).data("index");
        item = res[index];
        fillArticlePanel(item);
    });
    return node;
}

function generateTagListHtml(item, index){
    var ret='';

    for(var i=0;i<item.imgTagList.length;i++) {
        var tagName = item.imgTagList[i].tagName;
        if (tagName.length >= 8) {
            ret += '<em class="lable_s2 lable_cm del">\n' +
                '                        <span class="lable_txt">' + tagName + '</span>\n' +
                '                        <span class="l_s_b" onclick="removeSelf(this)"></span>\n' +
                '          </em>';
        } else {
            ret += '<em class="lable_s2 lable_cm del">\n' +
                '                        <span class="lable_txt">' + tagName + '</span>\n' +
                '                        <span class="l_s_b" onclick="removeSelf(this)"></span>\n' +
                '          </em>';
        }
    }
    ret+='<em class="lable_s3 lable_cm add hide" id="inputBlock'+index+'">\n' +
        '                        <input type="text" placeholder="请输入" class="lable_ipt j_taps_input" id="tagInput'+index+'">\n' +
        '                        <span class="l_s_b" onclick="addTag('+index+')"></span>\n' +
        '                    </em>';

    return ret;

}

function addNewArticle() {
    var title = $id("new_title").value;
    var content = $id("new_content").value;
    var docCategory = $id("new_category").value;
    $id("new_title").value = "";
    $id("new_content").value = "";
    $id("new_category").value = "0";
    console.info(docCategory + " " + title);
    var newArticle = {title: title, content: content, docCategory: docCategory};
    userArticles.unshift(newArticle);
    filterArticlesByCategory(0)
}

function fillArticlePanel(item){
    // console.log('content');
    // console.log(item.code);
    $("#articlePanel h2").html(item.title);

    $("p#content").html(item.content);
    //add image to panel
    $.ajax({
        url: apiHost + queriesUri,
        type: 'POST',
        dataType: 'json',
        headers: {
            "Content-Type": "application/json;charset=utf-8"
        },
        data: JSON.stringify({
            title: item.title,
            content: item.content,
            category: item.docCategory
        }),
        success: function (res) {
            var imgList = res.entity.imgList;
            $('#rightPanel').html('');
            imgList.forEach(function (item, index) {
                var html = '<div>' +
                    '<div style="padding: 5px;">\n' +
                    '                    <img src="'+item.imgOriginalURL+'" class="img-fluid" alt="Responsive image" data-toggle="modal" data-target="#confirm">\n' +
                    '                </div>\n' +
                    '                <div class="lable_box" id="tagSection'+index+'">\n' +
                    '                    <span class="label_s">Tags</span>\n' +
                    generateTagListHtml(item, index)+
                    '                </div>\n' +
                    '                <div class="star_box">\n' +
                    // '                    <span class="star_s">得分</span>\n' +
                    '                    <section class="star_box_s" id="star_box_s'+index+'">\n' +
                    '                        <em data-score="1" class="star"></em>\n' +
                    '                        <em data-score="2" class="star"></em>\n' +
                    '                        <em data-score="3" class="star"></em>\n' +
                    '                        <em data-score="4" class="star"></em>\n' +
                    '                        <em data-score="5" class="star"></em>\n' +
                    '                    </section>\n' +
                    '\n' +
                    '                </div>' +
                    '</div>';
                $('#rightPanel').append(html);
                // addTagInput(index);
                bindClickToStar(index);
            })
        }
    })
}

function bindClickToStar(index){
    $("section#star_box_s"+index).children().click(function(){
        var the = $(this).data("score");
        $("section#star_box_s"+index).children().each(function(){
            if($(this).data("score")<=the){
                $(this).addClass("active");
            }else{
                $(this).removeClass("active");
            }
        });
    });
}

function addTag(index){
    var input =  $("#tagInput"+index);
    var val = input.val();
    // console.log(val);
    if(!val){
        return;
    }
    removeTagInput(index);
    appendTag(val, index);
    addTagInput(index);
}

function removeTagInput(index){
    $("#inputBlock"+index).remove();
}

function addTagInput(index){
    var tagSection = $("#tagSection"+index);
    var html = '<em class="lable_s3 lable_cm add hide" id="inputBlock'+index+'">\n' +
        '                        <input type="text" placeholder="请输入" class="lable_ipt j_taps_input" id="tagInput'+index+'">\n' +
        '                        <span class="l_s_b" onclick="addTag('+index+')"></span>\n' +
        '                    </em>';
    tagSection.append(html);
}

function removeSelf(el){
    $(el).parent().remove();
}

function appendTag(text, index){
    var tagSection = $("#tagSection"+index);
    var txt = '<em class="lable_s2 lable_cm del">\n' +
        '                        <span class="lable_txt">'+text+'</span>\n' +
        '                        <span class="l_s_b" onclick="removeSelf(this)"></span>\n' +
        '                    </em>';
    tagSection.append(txt);

}

